package com.ruoyi.news.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.news.domain.dto.NewsDto;
import com.ruoyi.news.domain.vo.NewsVo;
import com.ruoyi.news.domain.query.NewsQuery;
import com.ruoyi.news.domain.pojo.News;

import com.ruoyi.news.enums.NewsStatus;
import com.ruoyi.news.mapper.NewsMapper;
import com.ruoyi.news.service.INewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import static com.fasterxml.jackson.databind.type.LogicalType.DateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lijuntao
 * @since 2025-06-21
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News> implements INewsService {
    private final NewsMapper newsMapper;

    @Override
    public List<NewsVo> listByPage(NewsQuery query) {
        Integer statusCode = (query.getStatus() != null)
                ? NewsStatus.fromString(query.getStatus()).getCode()
                : null;
        String searchValue = "";
//        List<News> list = newsMapper.listByPage(query.getTitle(),query.getTypeId(),query.getSource(),statusCode);
        // 使用 MyBatis-Plus 的 LambdaQueryWrapper
        List<News> list = lambdaQuery()
                .like(StringUtils.isNotBlank(query.getTitle()), News::getTitle, query.getTitle())
                .eq(query.getTypeId() != null, News::getTypeId, query.getTypeId())
                .eq(statusCode != null, News::getStatus, statusCode)
                .like(StringUtils.isNotBlank(query.getSource()), News::getSource, query.getSource())
                .list();


        List<NewsVo> newsVos = BeanUtil.copyToList(list, NewsVo.class);
        newsVos.forEach(newsVo -> {
            NewsStatus status = Arrays.stream(NewsStatus.values())
                    .filter(e -> e.getCode() == Integer.parseInt(newsVo.getStatus().toString()))
                    .findFirst()
                    .orElseThrow(() -> new IllegalArgumentException("无效的状态码: " + newsVo.getStatus()));
            newsVo.setStatus(status.getDesc());
        });
        return newsVos;
    }

    @Override
    public boolean deleteByIds(List<Integer> newsIds) {
        return lambdaUpdate().in(News::getNewsId, newsIds)
                .set(News::getStatus, NewsStatus.DELETED.getCode())
                .update();
    }


    @Override
    public int insertNews(NewsDto dto) {
        // 将 DTO 转换为 Entity
        News news = new News();
        BeanUtils.copyProperties(dto, news);

        // 处理状态转换
        if (StringUtils.isNotBlank(dto.getStatus())) {
            try {
                // 根据状态描述获取枚举值
                NewsStatus status = Arrays.stream(NewsStatus.values())
                        .filter(e -> e.getDesc().equals(dto.getStatus()))
                        .findFirst()
                        .orElseThrow(() -> new IllegalArgumentException("无效的状态描述: " + dto.getStatus()));
                news.setStatus(status.getCode());
            } catch (Exception e) {
                // 如果描述不匹配，尝试直接按枚举名称转换
                try {
                    NewsStatus status = NewsStatus.fromString(dto.getStatus());
                    news.setStatus(status.getCode());
                } catch (IllegalArgumentException ex) {
                    throw new IllegalArgumentException("无效的状态值，请使用: 删除/正常/发布/延时发布");
                }
            }
        } else {
            // 默认状态
            news.setStatus(NewsStatus.NORMAL.getCode());
        }

        // 设置创建时间
        news.setCreateTime(new Date());

        // 执行插入操作
        return baseMapper.insert(news);
    }

    //修改新闻
    @Override
    public void updateNews(NewsDto dto) {
        News news = new News();

        //赋值
        if (Objects.equals(dto.getStatus(), "正常")) {
            news.setStatus(NewsStatus.NORMAL.getCode());
        } else if (Objects.equals(dto.getStatus(), "删除")) {
            news.setStatus(NewsStatus.DELETED.getCode());
        } else {
            news.setStatus(5);
        }

        //转换
        news.setNewsId(dto.getNewsId());
        news.setTitle(dto.getTitle());
        news.setContent(dto.getContent());
        news.setTypeId(dto.getTypeId());
        news.setDelayTime(dto.getDelayTime());
        news.setSource(dto.getSource());
        news.setCreateBy(dto.getCreateBy());
        news.setUpdateBy(dto.getUpdateBy());
        news.setRemark(dto.getRemark());
        news.setUpdateTime(new Date());
        news.setParams(dto.getParams());

        log.info("修改新闻参数：{}", dto);
        if (dto.getNewsId() != null) {
            // 查询新闻
            News one = lambdaQuery().eq(News::getNewsId, dto.getNewsId()).one();
            //json序列化
            String json = JSON.toJSONString(one);
            // 修改
            int flag = newsMapper.updateById(news);
            if (flag > 0) {
                log.info("修改新闻成功");

            } else {
                throw new RuntimeException("修改新闻失败");

            }
        }
    }



}
